package com.ccnu.sb.controller;

import com.ccnu.sb.dao.pojo.TCust;
import com.ccnu.sb.exception.RspException;
import com.ccnu.sb.manage.LoginMan;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
public class AppController {
	private final Logger log = LoggerFactory.getLogger(AppController.class);
	
	@Autowired
	private LoginMan loginmanage;
	
	@RequestMapping("/")
	public String Index() {
		log.info("LoginController.Index entry");
		return "index.html";
	}
	
	@ResponseBody
	@RequestMapping(value="/signup", method=RequestMethod.POST)
	public String AppSignUp(@RequestBody(required=true) Map<String,Object> reqMap) {
		String RspInfo = "";
		try {
			RspInfo = loginmanage.SignUp(reqMap);
		} catch (RspException e) {
			RspInfo = e.getErrorInfo();
		}
		return RspInfo;
	}
	
	@ResponseBody
	@RequestMapping(value="/login", method=RequestMethod.POST)
	public String AppLogin(@RequestBody(required=true) Map<String,Object> reqMap) {
		String RspInfo = "";
		try {
			RspInfo = loginmanage.Login(reqMap);
		} catch (RspException e) {
			RspInfo = e.getErrorInfo();
		}
		return RspInfo;
	}
	
	@ResponseBody
	@RequestMapping(value="/redis", method=RequestMethod.GET)
	public String RedisUserInfo(Map<String,Object> reqMap) {
		String RspInfo = "";
		try {
			RspInfo = String.valueOf(loginmanage.CacheUser(reqMap));
		} catch (RspException e) {
			RspInfo = e.getErrorInfo();
		}
		return RspInfo;
	}
	
	@ResponseBody
	@RequestMapping(value="/redis/listuser", method=RequestMethod.GET)
	public String RedisListUser(Map<String,Object> reqMap) {
		String RspInfo = "";
		List<TCust> userList = null;
		try {
			userList = loginmanage.ListCacheUser();
			ObjectMapper mapper = new ObjectMapper();
			try {
				RspInfo = mapper.writeValueAsString(userList);
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
		} catch (RspException e) {
			RspInfo = e.getErrorInfo();
		}
		return RspInfo;
	}
}
